package com.iniapp.app.web.action;

import java.io.Serializable;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.iniapp.app.jsf.Credentials;
import com.iniapp.app.jsf.Identity;
import com.iniapp.app.jsf.JSFUtility;
import com.inibb.app.service.security.IUserService;
import com.inibb.app.util.SecurityUtils;
import com.inibb.app.vo.security.UserVO;

@Controller("authenticationCtrl")
@Scope("request")
public class AuthenticationCtrl implements Serializable {

	private static final long serialVersionUID = 1L;

	@Autowired
	private Credentials credentials;
	@Autowired
	private Identity identity;
	@Autowired
	private IUserService userService;

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private Identity dbLogin() {

		logger.info("Starting db login, if this method is called after NTML auth, then, password hash comparision is not required.");

		UserVO user = userService.getUserByLoginName(credentials.getUsername());

		if (user != null) {

			logger.debug("Method-call is not after NTML, start comparing password hash.");
			String hash = SecurityUtils.createPasswordHash(credentials.getPassword());
			String pass = StringUtils.trimToEmpty(user.getPassword());

			if (hash.equals(pass)) {
				identity.setAuthenticated(true);
				logger.info("Password is correct, {} have successfully logged on to DB.", credentials.getUsername());

			} else {
				logger.info("Password is incorrect, DB logon failed.");
				identity.setAuthenticated(false);

			}

			if (identity.isAuthenticated()) {
				identity.setActivated(true);
			}

			if (identity.isActivated()) {
				this.credentials.setUsername(user.getLoginName());
				this.identity.setUsername(user.getName());
				this.identity.setUserId(user.getId());
				logger.info("Successfully logged into system.");
				identity.setLoggedIn(true);
				//get granted urls
				identity.addGrantedUrls(userService.searchGrantedUrls(user.getId()));
				
			} else {
				logger.info("Failed to log into system.");
				identity.setLoggedIn(false);
			}

		} else {
			logger.info("DB logon failed.");
			identity.setAuthenticated(false);
		}

		return identity;
	}

	public String login() {
		// credentials.setUsername(StringUtils.upperCase(credentials.getUsername()));
		this.identity = dbLogin();
		if (identity.isLoggedIn()) {
			if (identity.isForceToChangePassword()) {
				return "changePassword";
			}
			return "loggedIn";
		} else {
			return "loginFailed";
		}
	}

	public String logout() {
		logger.info("Logging out system.");
		HttpSession session = (HttpSession) JSFUtility.getFacesContext().getExternalContext().getSession(false);
		if (session != null) {
			session.invalidate();
		}

		return "logout";
	}

}
